package com.wd.tw.websocket.client;

import com.wd.tw.config.AppConfig;
import com.wd.tw.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * WebSocket客户端配置类
 */
@Configuration
@Slf4j
public class WebSocketClientConfig {

    @Resource
    AppConfig appConfig;

    @Resource
    TokenService tokenService;

    /**
     * socket连接地址
     */
//    @Value("${honsvr.socket.url}")
//    private String webSocketUri="ws://18.18.10.30/edgeboxapi/websocket/open?token=eyJ2ZXIiOiIxLjAifQ==.eyJzaWduX3RpbWUiOiIxNzMyMDk1NTM2IiwiZXhwaXJlX3RpbWUiOiIxNzMyMTA5OTU2IiwiY2xpZW50X3R5cGUiOiIwIiwidXNlcl9pZCI6IntFOEYxMDBDQy05N0U2LTQ1OEMtQTlGMS0zQjQzRkU2MzBBRDB9IiwidXNlcl9yb2xlX2lkIjoiMSJ9.Q5vGuCMzaVTvH8srtjD2p38HGyo+jk7Pvo8uJXZZXBU=";

    /**
     * 注入Socket客户端
     *
     * @return
     */
//    @Bean
    public CustomizedWebSocketClient initWebSocketClient() {

        String webSocketUri = appConfig.getWsUrl() + "/open?token=" + tokenService.getToken();

        URI uri = null;
        try {
            uri = new URI(webSocketUri);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        log.info("begin to connect websocket:" + webSocketUri);
        CustomizedWebSocketClient webSocketClient = new CustomizedWebSocketClient(uri);

        // 设置连接丢失的超时时间为60秒
        webSocketClient.setConnectionLostTimeout(60 * 60 * 24 * 7);

        //启动时创建客户端连接
        webSocketClient.connect();
        return webSocketClient;
    }

}
